package cn.wx.jove.tool.jwt;

import cn.wx.common.persistence.exception.MyException;
import cn.wx.common.persistence.redisson.RS;
import cn.wx.common.persistence.web.ResponseCode;
import cn.wx.common.persistence.web.ResponseData;
import com.alibaba.fastjson.JSON;
import org.redisson.api.RMapCache;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * jwt拦截器
 */
public class JwtAuthFilter {

	@Autowired
	private RedissonClient redissonClient;

	public Boolean filterInternal(HttpServletResponse response, String token) throws ServletException, IOException {
		
		try {

			/**
			 * 先验证token是否合法
			 */
			Long pId = JwtUtil.validateToken(token);
			
			/**
			 * 看服务中的缓存 是否存在
			 */
			//RSetCache<String> tokenSet = redissonClient.getSetCache(RS.REDIS_GENETOKEN);
			
			RMapCache<Long,String> tokens = redissonClient.getMapCache(RS.REDIS_GENETOKEN);
			
			if(!tokens.containsValue(token)){
				throw new MyException(ResponseCode.JWT_CHECK_ERROR);
			}
			/**
			 * 每一次验证成功之后 延长token的时长
			 */
			tokens.put(pId, token, 30, TimeUnit.MINUTES);
			return true;
			
		} catch (Exception e) {
			response.setContentType("application/json;charset=utf-8");
			response.setStatus(200);
			response.setCharacterEncoding("utf-8");
			try {
				response.getWriter().write(JSON.toJSONString(ResponseData.ERROR("10001","token认证错误！",e.getMessage())));
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
			return false;
		}
	}

	
}